package com.jcsz.gulimall.cart.interceptor;

import com.jcsz.common.constant.AuthServerConstant;
import com.jcsz.common.constant.CartConstant;
import com.jcsz.common.vo.MemberRespVo;
import com.jcsz.gulimall.cart.to.UserInfoTo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @className: CartInterceptor
 * @author: 一把Po吉他
 * @date: 2022/11/10 12:06
 * 拦截器：任何请求过来都需要先经过拦截器
 * 实现方式：实现HandlerInterceptor接口 重新对应方法
 * preHandle 预处理 请求前
 * postHandle 后处理 请求完成后
 * afterCompletion 请求结束后
 * 在执行目标方法之前，先来判断用户的状态
 * 保证购物车所有请求一进来，先能获取到用户的信息，无论是临时还是登录后的信息
 **/
@Component
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        MemberRespVo memberEntity = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        //封装用户登录状态信息
        UserInfoTo userInfoTo = new UserInfoTo();
        if (memberEntity != null) {
            //登录用户
            userInfoTo.setUserId(memberEntity.getId());
        }
        //判断是否为拥有临时用户
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //临时用户状态
                if (cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        //给一个临时用户的key
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //获取当前用户的值
        UserInfoTo userInfoTo = threadLocal.get();
        // 如果没有临时用户，一定要保存一个临时用户
        if (!userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }

    }

}
